<template>
  <div class="user-list-container">
    <!-- 表格 -->
    <el-card shadow="never" class="table-card">
      <div style="display: flex; margin-bottom: 20px">
        <el-button type="primary" @click="openAddDialog">创建</el-button>
      </div>
      <el-table v-loading="loading" :data="tableData" border class="table">
        <el-table-column prop="role_id" label="ID" width="80" />
        <el-table-column prop="role_name" label="角色名称" />
        <el-table-column prop="created_at" label="创建时间" />
        <el-table-column label="操作" width="240">
          <template #default="scope">
            <el-button link @click="handleTableOption('edit', scope.row)">编辑</el-button>
            <el-button link @click="handleTableOption('editPermission', scope.row)">编辑权限</el-button>
            <el-button link type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination class="pagination" @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="page" :page-sizes="[10, 20, 30, 50]" :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper" :total="total" />
    </el-card>

    <!-- 创建/编辑角色对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogType === 'edit' ? '编辑角色' : '创建角色'" width="600"
      :before-close="handleCloseAddDialog">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px" class="demo-form">
        <el-form-item label="角色名称" prop="role_name">
          <el-input v-model="form.role_name" placeholder="请输入角色名称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCloseAddDialog">取消</el-button>
          <el-button type="primary" @click="submitForm">
            保存
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 编辑权限对话框 -->
    <el-dialog v-model="permissionDialogVisible" title="编辑权限" width="800" :before-close="handleClosePermissionDialog">
      <el-form label-width="100px">
        <el-form-item label="角色名称">
          <el-input v-model="currentRole.role_name" disabled />
        </el-form-item>
        <el-form-item label="权限设置">
          <div class="permission-tree-container">
            <el-tree ref="permissionTree" :data="permissionTree" show-checkbox node-key="menu_id" :props="treeProps"
              :default-expand-all="true" :check-strictly="false" />
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClosePermissionDialog">取消</el-button>
          <el-button type="primary" @click="submitPermissionForm">
            保存权限
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import tableMixin from "@/mixins/tableMixin";
import api from "@/request/api.js";

export default {
  name: "RoleList",
  mixins: [tableMixin],
  data() {
    return {
      // 查询参数
      queryParams: {},
      apimodel: "getrokist",
      apival: "getList",

      // 对话框控制
      dialogVisible: false,
      permissionDialogVisible: false,
      dialogType: "",

      // 表单数据
      form: {
        role_id: "",
        role_name: "",
      },
      rules: {
        role_name: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
        ],
      },

      // 权限相关
      permissionTree: [],
      treeProps: {
        children: "treeList",
        label: "title",
      },
      currentRole: {},
      rolePermissions: [], // 当前角色的权限ID数组
    };
  },
  created() {
    this.getPermissionTree();
  },
  methods: {
    // 获取权限树
    async getPermissionTree() {
      try {
        const res = await api.getrokist.getMenuListByTreeList();
        if (res.data.code === 200) {
          this.permissionTree = res.data.content.data;
        }
      } catch (error) {
        console.error("获取权限树失败:", error);
      }
    },

    // 获取角色已有权限
    async getRolePermissions(roleId) {
      try {
        const res = await api.getrokist.getPermissions({ role_id: roleId });
        if (res.data.code === 200) {
          // 假设返回的数据格式为 { menu_id: 3 }, { menu_id: 4 }...
          let data = res.data.content.data;
          let result = data.map(item => ({ menu_id: item }));
          this.rolePermissions = result.map(item => item.menu_id);

          // 设置树形控件的选中状态
          this.$nextTick(() => {
            // 先取消所有选中
            this.$refs.permissionTree.setCheckedKeys([]);

            // 再设置新的选中项（包括半选中状态）
            this.$refs.permissionTree.setCheckedKeys(this.rolePermissions);

            // 如果需要处理父节点的半选中状态（可选）
            // 有些树组件需要手动处理父节点的选中状态
            this.updateTreeHalfChecked();
          });
        }
      } catch (error) {
        console.error("获取角色权限失败:", error);
      }
    },
    updateTreeHalfChecked() {
      const tree = this.$refs.permissionTree;
      const checkedKeys = tree.getCheckedKeys();
      const halfCheckedKeys = [];

      // 递归检查每个节点的父节点是否需要半选中
      const checkParentHalfChecked = (node) => {
        const parent = tree.getNode(node.parent);
        if (!parent) return;

        const allChildren = parent.childNodes || [];
        const checkedChildren = allChildren.filter(child =>
          checkedKeys.includes(child.key) || halfCheckedKeys.includes(child.key)
        );

        if (checkedChildren.length > 0 && checkedChildren.length < allChildren.length) {
          halfCheckedKeys.push(parent.key);
        }

        checkParentHalfChecked(parent);
      };

      // 对每个选中的节点检查其父节点
      checkedKeys.forEach(key => {
        const node = tree.getNode(key);
        if (node) checkParentHalfChecked(node);
      });

      // 重新设置选中状态（包括半选中）
      tree.setCheckedKeys([...checkedKeys, ...halfCheckedKeys]);
    },
    // 打开创建/编辑对话框
    openAddDialog(option = "") {
      this.dialogVisible = true;
      this.dialogType = option;
    },

    // 关闭创建/编辑对话框
    handleCloseAddDialog() {
      this.dialogVisible = false;
      this.form = {
        role_id: "",
        role_name: "",
      };
      this.$refs.formRef?.resetFields();
    },

    // 打开权限编辑对话框
    async handleTableOption(option, row) {
      if (option === "edit") {
        this.form = JSON.parse(JSON.stringify(row));
        this.openAddDialog(option);
      } else if (option === "editPermission") {
        this.currentRole = JSON.parse(JSON.stringify(row));
        this.permissionDialogVisible = true;
        await this.getRolePermissions(row.role_id);
      }
    },

    // 关闭权限编辑对话框
    handleClosePermissionDialog() {
      this.permissionDialogVisible = false;
      this.currentRole = {};
      this.rolePermissions = [];
    },

    // 提交表单（创建/编辑角色）
    submitForm() {
      this.$refs.formRef.validate(async (valid) => {
        if (valid) {
          try {
            let res;
            if (this.dialogType === "edit") {
              let a = {
                role_id: this.form.role_id,
                role_name: this.form.role_name
              }
              res = await api.getrokist.update(a);
            } else {
              res = await api.getrokist.create(this.form);
            }

            if (res.data.code === 200) {
              this.$message.success(this.dialogType === "edit" ? "修改成功" : "创建成功");
              this.handleCloseAddDialog();
              this.getTableData();
            }
          } catch (error) {
            console.error("操作失败:", error);
          }
        }
      });
    },

    // 提交权限表单
    async submitPermissionForm() {
      try {
        // 获取选中的节点（包括半选中的父节点）
        const checkedKeys = this.$refs.permissionTree.getCheckedKeys();
        const halfCheckedKeys = this.$refs.permissionTree.getHalfCheckedKeys();
        const allKeys = [...checkedKeys, ...halfCheckedKeys];

        const params = {
          role_id: this.currentRole.role_id,
          menu_list: allKeys,
        };

        const res = await api.getrokist.setPermissions(params);
        if (res.data.code === 200) {
          this.$message.success("权限设置成功");
          this.handleClosePermissionDialog();
        }
      } catch (error) {
        console.error("权限设置失败:", error);
      }
    },

    // 删除角色
    handleDelete(row) {
      this.$confirm("确认删除该角色吗?", "提示", {
        type: "warning",
      })
        .then(async () => {
          try {
            const res = await api.getrokist.del({ role_id: row.role_id });
            if (res.data.code === 200) {
              this.$message.success("删除成功");
              this.getTableData();
            }
          } catch (error) {
            console.error("删除失败:", error);
          }
        })
        .catch(() => { });
    },
  },
};
</script>

<style scoped>
.user-list-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.permission-tree-container {
  max-height: 500px;
  overflow-y: auto;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 10px;
}

.dialog-footer {
  text-align: right;
}
</style>